import Taro from '@tarojs/taro'
import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import api from '@API'
import {
  UPDATE_USER_BY_WECHAT_INFO, UPDATE_PROFILE, UPDATE_PROFILE_AVATAR, GET_PROFILE
} from '@ACTIONS/profile'
import { ProfileActionITF } from '@REDUXITF/profile'
import { ProfileITF, WeChatITF } from '@INTERFACES/user'
import { getUser } from './dataSelect'

const saveUserStorage = (data: string) => {
  Taro.setStorage({
    key: 'user',
    data,
  })
}

const updateProfileByWeChat = function* updateProfileByWeChat(action: ProfileActionITF) {
  try {
    const params = action.params as WeChatITF
    const data = yield call(api.updateUserByWeChatInfo, { ...params })
    saveUserStorage(data)
    yield put({ type: UPDATE_USER_BY_WECHAT_INFO.SUCCESS, data })
  } catch (error) {
    yield put({ type: UPDATE_USER_BY_WECHAT_INFO.FAILURE })
  }
}

const updateProfile = function* updateProfile(action: ProfileActionITF) {
  try {
    const params = action.params as ProfileITF
    const data = yield call(api.updateUserProfile, { ...params })
    saveUserStorage(data)
    Taro.showToast({
      icon: 'success',
      title: '保存成功',
      duration: 1000,
      mask: true,
      success: () => {
        setTimeout(Taro.navigateBack, 1000)
      }
    })
    yield put({ type: UPDATE_PROFILE.SUCCESS, data })
  } catch (error) {
    yield put({ type: UPDATE_PROFILE.FAILURE })
  }
}

const updateAvatar = function* updateAvatar() {
  try {
    const { NewAvatarVersion } = yield call(api.setUserAvatarVersion, {})
    const data = yield select(getUser)
    yield put({ type: UPDATE_PROFILE_AVATAR.SUCCESS, NewAvatarVersion })
    saveUserStorage({ ...data, AvatarVersion: NewAvatarVersion })
  } catch (error) {
    yield put({ type: UPDATE_PROFILE_AVATAR.FAILURE })
  }
}
const getProfile = function* getProfile() {
  try {
    const data = yield call(api.getLandingProfile, {})
    if (!data) return
    if (data?.AcquireChannel === 'Visitor') return
    yield put({ type: GET_PROFILE.SUCCESS, data })
  } catch (error) {
    yield put({ type: GET_PROFILE.FAILURE })
  }
}

export default function* rootSaga() : Generator {
  yield all([
    takeLatest(UPDATE_USER_BY_WECHAT_INFO.REQUEST, updateProfileByWeChat),
    takeLatest(UPDATE_PROFILE.REQUEST, updateProfile),
    takeLatest(UPDATE_PROFILE_AVATAR.REQUEST, updateAvatar),
    takeLatest(GET_PROFILE.REQUEST, getProfile),
  ]);
}
